package org.jeecg.modules.sms.hyrApi.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.Md5Util;
import org.jeecg.modules.sms.hyrApi.responseVo.HrySmsRtn;
import org.jeecg.modules.sms.sms.enums.DxtdlxEnum;
import org.jeecg.modules.sms.sms.param.SmsParam;
import org.jeecg.modules.sms.sms.vo.SmsRtn;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 华瑞云短信服务
 */
@Component
@Slf4j
public class HryRequestUtil {
    private final static String appKey = "Y9u9B5";
    private final static String appSecret = "0fRCAz";
    private final static String appCode = "1000";


    public static enum APIURL {
        SendSmsBatch("相同内容群发", "http://sms.huaruiyunapi.com/sms/batch/v1");
        private final String desc;//描述
        private final String url;//值

        APIURL(String desc, String url) {
            this.desc = desc;
            this.url = url;
        }
    }

    /**
     * 一对一内容群发
     * @param sms
     * @return
     */
    public Result<SmsRtn> sendBatch(SmsParam sms) {
        JSONObject param = getCommonParam();
        param.put("uid",sms.getUid());
        param.put("phone",sms.getPhone());
        param.put("msg",sms.getMsg());
        param.put("extend",sms.getExtend());
        String result = doPostJson(APIURL.SendSmsBatch.url, param.toJSONString());
        JSONObject jsonObject = JSONObject.parseObject(result);

        if(jsonObject.getString("code").equals("00000")) {//成功
            String uid = jsonObject.getString("uid");
            JSONArray jsonResult = jsonObject.getJSONArray("result");
            List<HrySmsRtn> rtnList = JSONArray.parseArray(jsonResult.toJSONString(), HrySmsRtn.class);

            List<SmsRtn.Fsjg> fsjgList = new ArrayList<>();
            rtnList.forEach(hrySmsRtn -> {
                SmsRtn.Fsjg fsjg = new SmsRtn.Fsjg();
                BeanUtils.copyProperties(hrySmsRtn,fsjg);
                if("00000".equals(hrySmsRtn.getStatus())){
                    fsjg.setCode("200");
                } else {
                    fsjg.setCode(hrySmsRtn.getStatus());
                }
                fsjg.setMsg(hrySmsRtn.getDesc());
                fsjg.setUid(uid);
                fsjgList.add(fsjg);
            });
            SmsRtn smsRtn = new SmsRtn();
            smsRtn.setDxtdlx(DxtdlxEnum.HYR.getValue());
            smsRtn.setUid(uid);
            smsRtn.setFsjg(fsjgList);
            return Result.OK("发送成功",smsRtn);
        } else {
            return Result.error(jsonObject.getString("desc"));
        }
    }

    private JSONObject getCommonParam() {
        long timestamp = System.currentTimeMillis();
        JSONObject param = new JSONObject();
        param.put("appkey", appKey);
        param.put("appcode", appCode);

        String sign = appKey +appSecret + timestamp;
        sign = Md5Util.md5Encode(sign,"utf-8");
        param.put("sign", sign);
        param.put("timestamp", timestamp);

        return param;
    }


    private String doPostJson(String url, String json) {
        return doPostJson(url, json, null);
    }
    private String doPostJson(String url, String json, Map<String, Object> headerMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if(headerMap != null) {
                Iterator<String> it = headerMap.keySet().iterator();
                while(it.hasNext()){
                    String key = it.next();
                    String value = String.valueOf(headerMap.get(key));
                    httpPost.setHeader(key,value);
                }
            }

            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            if (response == null) {
                log.info("http请求url{}异常，返回结果null,", url);
                return null;
            }
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
}
